<?php


namespace app\api\controller\v42;

use app\api\controller\v2\Auth;
use app\common\cachemodel\UserCoupon;
use app\common\cachemodel\ZlCouponAttr;
use app\common\cachemodel\ZlYearActiveCouponRecord;
use app\common\cachemodel\ZlYearActiveText;
use app\common\cachemodel\ZlYearActiveTextChangeRecode;
use app\common\lib\exception\ApiException;
use app\common\lib\SensorsData;
use app\common\lib\Util;
use app\common\model\Goods;
use app\zyhsapi\model\ZyhsUser;
use app\zyhsapi\model\ZyhsUserCoupon;
use think\Cache;
use think\Controller;
use think\Env;
use think\Log;
use think\response\Json;

class YearActiv extends Controller
{
    private $activeConfig = [
        'coupon' => [ // 免费券领取【实现方式：优惠券兑换码领取】  每人限领一张
            209 => [ // 2024-02-09
                1 => [
                    1 => [
                        'start_time' => 1707451200,       // 活动开始时间戳 2024-02-09 12:00:00
                        'end_time' => 1707494400,   // 活动结束时间戳 2024-02-10 00:00:00
                        'coupon_num' => 105,  // 发放数量
                    ],
                    2 => [
                        'start_time' => 1707480000,       // 活动开始时间戳 2024-02-09 20:00:00
                        'end_time' => 1707494400,   // 活动结束时间戳 2024-02-10 00:00:00
                        'coupon_num' => 105,  // 发放数量
                    ],
                ],
                2 => [
                    1 => [
                        'start_time' => 1707451200,       // 活动开始时间戳 2024-02-09 12:00:00
                        'end_time' => 1707494400,   // 活动结束时间戳 2024-02-10 00:00:00
                        'coupon_num' => 100,  // 发放数量
                    ],
                    2 => [
                        'start_time' => 1707480000,       // 活动开始时间戳 2024-02-09 20:00:00
                        'end_time' => 1707494400,   // 活动结束时间戳 2024-02-10 00:00:00
                        'coupon_num' => 100,  // 发放数量
                    ],
                ],
                'date' => '除夕',
            ],
            210 => [ // 2024-02-10
                1 => [
                    1 => [
                        'start_time' => 1707537600,       // 活动开始时间戳 2024-02-10 12:00:00
                        'end_time' => 1707580800,   // 活动结束时间戳 2024-02-11 00:00:00
                        'coupon_num' => 105,  // 发放数量
                    ],
                    2 => [
                        'start_time' => 1707566400,       // 活动开始时间戳 2024-02-10 20:00:00
                        'end_time' => 1707580800,   // 活动结束时间戳 2024-02-11 00:00:00
                        'coupon_num' => 105,  // 发放数量
                    ],
                ],
                2 => [
                    1 => [
                        'start_time' => 1707537600,       // 活动开始时间戳 2024-02-10 12:00:00
                        'end_time' => 1707580800,   // 活动结束时间戳 2024-02-11 00:00:00
                        'coupon_num' => 100,  // 发放数量
                    ],
                    2 => [
                        'start_time' => 1707566400,       // 活动开始时间戳 2024-02-10 20:00:00
                        'end_time' => 1707580800,   // 活动结束时间戳 2024-02-11 00:00:00
                        'coupon_num' => 100,  // 发放数量
                    ],
                ],
                'date' => '初一',
            ],
            211 => [ // 2024-02-11
                1 => [
                    1 => [
                        'start_time' => 1707624000,       // 活动开始时间戳 2024-02-11 12:00:00
                        'end_time' => 1707667200,   // 活动结束时间戳 2024-02-12 00:00:00
                        'coupon_num' => 105,  // 发放数量
                    ],
                    2 => [
                        'start_time' => 1707652800,       // 活动开始时间戳 2024-02-11 20:00:00
                        'end_time' => 1707667200,   // 活动结束时间戳 2024-02-12 00:00:00
                        'coupon_num' => 105,  // 发放数量
                    ],
                ],
                2 => [
                    1 => [
                        'start_time' => 1707624000,       // 活动开始时间戳 2024-02-11 12:00:00
                        'end_time' => 1707667200,   // 活动结束时间戳 2024-02-12 00:00:00
                        'coupon_num' => 100,  // 发放数量
                    ],
                    2 => [
                        'start_time' => 1707652800,       // 活动开始时间戳 2024-02-11 20:00:00
                        'end_time' => 1707667200,   // 活动结束时间戳 2024-02-12 00:00:00
                        'coupon_num' => 100,  // 发放数量
                    ],
                ],
                'date' => '初二',
            ],
            212 => [ // 2024-02-12
                1 => [
                    1 => [
                        'start_time' => 1707710400,       // 活动开始时间戳 2024-02-12 12:00:00
                        'end_time' => 1707753600,   // 活动结束时间戳 2024-02-13 00:00:00
                        'coupon_num' => 105,  // 发放数量
                    ],
                    2 => [
                        'start_time' => 1707739200,       // 活动开始时间戳 2024-02-12 20:00:00
                        'end_time' => 1707753600,   // 活动结束时间戳 2024-02-13 00:00:00
                        'coupon_num' => 105,  // 发放数量
                    ],
                ],
                2 => [
                    1 => [
                        'start_time' => 1707710400,       // 活动开始时间戳 2024-02-12 12:00:00
                        'end_time' => 1707753600,   // 活动结束时间戳 2024-02-13 00:00:00
                        'coupon_num' => 100,  // 发放数量
                    ],
                    2 => [
                        'start_time' => 1707739200,       // 活动开始时间戳 2024-02-12 20:00:00
                        'end_time' => 1707753600,   // 活动结束时间戳 2024-02-13 00:00:00
                        'coupon_num' => 100,  // 发放数量
                    ],
                ],
                'date' => '初三',
            ],
            213 => [ // 2024-02-13
                1 => [
                    1 => [
                        'start_time' => 1707796800,       // 活动开始时间戳 2024-02-13 12:00:00
                        'end_time' => 1707840000,   // 活动结束时间戳 2024-02-14 00:00:00
                        'coupon_num' => 105,  // 发放数量
                    ],
                    2 => [
                        'start_time' => 1707825600,       // 活动开始时间戳 2024-02-13 20:00:00
                        'end_time' => 1707840000,   // 活动结束时间戳 2024-02-14 00:00:00
                        'coupon_num' => 105,  // 发放数量
                    ],
                ],
                2 => [
                    1 => [
                        'start_time' => 1707796800,       // 活动开始时间戳 2024-02-13 12:00:00
                        'end_time' => 1707840000,   // 活动结束时间戳 2024-02-14 00:00:00
                        'coupon_num' => 100,  // 发放数量
                    ],
                    2 => [
                        'start_time' => 1707825600,       // 活动开始时间戳 2024-02-13 20:00:00
                        'end_time' => 1707840000,   // 活动结束时间戳 2024-02-14 00:00:00
                        'coupon_num' => 100,  // 发放数量
                    ],
                ],
                'date' => '初四',
            ],
            214 => [ // 2024-02-14
                1 => [
                    1 => [
                        'start_time' => 1707883200,       // 活动开始时间戳 2024-02-14 12:00:00
                        'end_time' => 1707926400,   // 活动结束时间戳 2024-02-15 00:00:00
                        'coupon_num' => 105,  // 发放数量
                    ],
                    2 => [
                        'start_time' => 1707912000,       // 活动开始时间戳 2024-02-14 20:00:00
                        'end_time' => 1707926400,   // 活动结束时间戳 2024-02-15 00:00:00
                        'coupon_num' => 105,  // 发放数量
                    ],
                ],
                2 => [
                    1 => [
                        'start_time' => 1707883200,       // 活动开始时间戳 2024-02-14 12:00:00
                        'end_time' => 1707926400,   // 活动结束时间戳 2024-02-15 00:00:00
                        'coupon_num' => 100,  // 发放数量
                    ],
                    2 => [
                        'start_time' => 1707912000,       // 活动开始时间戳 2024-02-14 20:00:00
                        'end_time' => 1707926400,   // 活动结束时间戳 2024-02-15 00:00:00
                        'coupon_num' => 100,  // 发放数量
                    ],
                ],
                'date' => '初五',
            ],
            215 => [ // 2024-02-15
                1 => [
                    1 => [
                        'start_time' => 1707969600,       // 活动开始时间戳 2024-02-15 12:00:00
                        'end_time' => 1708012800,   // 活动结束时间戳 2024-02-16 00:00:00
                        'coupon_num' => 105,  // 发放数量
                    ],
                    2 => [
                        'start_time' => 1707998400,       // 活动开始时间戳 2024-02-15 20:00:00
                        'end_time' => 1708012800,   // 活动结束时间戳 2024-02-16 00:00:00
                        'coupon_num' => 105,  // 发放数量
                    ],
                ],
                2 => [
                    1 => [
                        'start_time' => 1707969600,       // 活动开始时间戳 2024-02-15 12:00:00
                        'end_time' => 1708012800,   // 活动结束时间戳 2024-02-16 00:00:00
                        'coupon_num' => 100,  // 发放数量
                    ],
                    2 => [
                        'start_time' => 1707998400,       // 活动开始时间戳 2024-02-15 20:00:00
                        'end_time' => 1708012800,   // 活动结束时间戳 2024-02-16 00:00:00
                        'coupon_num' => 100,  // 发放数量
                    ],
                ],
                'date' => '初六',
            ],
            216 => [ // 2024-02-16
                1 => [
                    1 => [
                        'start_time' => 1708056000,       // 活动开始时间戳 2024-02-16 12:00:00
                        'end_time' => 1708099200,   // 活动结束时间戳 2024-02-17 00:00:00
                        'coupon_num' => 105,  // 发放数量
                    ],
                    2 => [
                        'start_time' => 1708084800,       // 活动开始时间戳 2024-02-16 20:00:00
                        'end_time' => 1708099200,   // 活动结束时间戳 2024-02-17 00:00:00
                        'coupon_num' => 105,  // 发放数量
                    ],
                ],
                2 => [
                    1 => [
                        'start_time' => 1708056000,       // 活动开始时间戳 2024-02-16 12:00:00
                        'end_time' => 1708099200,   // 活动结束时间戳 2024-02-17 00:00:00
                        'coupon_num' => 100,  // 发放数量
                    ],
                    2 => [
                        'start_time' => 1708084800,       // 活动开始时间戳 2024-02-16 20:00:00
                        'end_time' => 1708099200,   // 活动结束时间戳 2024-02-17 00:00:00
                        'coupon_num' => 100,  // 发放数量
                    ],
                ],
                'date' => '初七',
            ],
        ],
        'text_exchange' => [
            'text1' => [
                'exchange_num' => 1,// 允许兑换次数
                'year_fortune_cid' => 761,
                'month_fortune_cid' => 760,
                'day_fortune_cid' => 759,
            ],
            'text2' => [
                'exchange_num' => 1,// 允许兑换次数
                'dating_cid' => 753,   // 婚姻
                'academic_cid' => 754,   // 学业
                'carrer_cid' => 756,   // 事业
                'money_cid' => 752,   // 财富
                'feelings_cid' => 755,   // 恋爱
            ],
        ],
        'sign_in' => [
            'start_time' => 1707408000, //2024-02-09 00:00:00
            'end_time' => 1708099200,   //2024-02-17 00:00:00
        ],
    ];

    protected $user = null;
    protected $text = ['2024', '愉', '跃', '龙', '门'];
    protected $activeFlag = 2024;
    protected $time;

    public function _initialize()
    {
        parent::_initialize();
        $time = Cache::get('2024:year:active:test_time', false);
        $this->time = $time ? strtotime($time) : time();


        $action = $this->request->action();

        try
        {
            $auth = new Auth();
            $this->user = $auth->user;
        }
        catch (\Exception $e)
        {
            if ($action === 'index')
            {
                if ($e->getCode() !== 0)
                {
                    throw new ApiException($e->getMessage(), 200, $e->getCode());
                }
            } else
            {
                throw new ApiException($e->getMessage(), 200, $e->getCode());
            }
        }
    }

    /**
     * 春节活动首页
     */
    public function index()
    {
        $isLogin = $this->user ? true : false;
        $uid = $isLogin ? $this->user['id'] : 0;
        $uen = input('uen/s', '');
        $requestText = input('text/s', '');
        $date = (int)(date('md', $this->time));

        $couponRecordModel = new ZlYearActiveCouponRecord();
        $activeTextChangeRecodeModel = new ZlYearActiveTextChangeRecode();
        $yearActiveTextModel = new ZlYearActiveText();

        $giveCouponActive = [];
        foreach ($this->activeConfig['coupon'] as $day => $item)
        {
            $status = 1 + ($date <=> $day);   // 0=>未开始 1=>进行中 2=>已结束

            if ($status === 0)
            {   // 未开始
                $btn1Status = 0;
                $btn2Status = 0;
            } elseif ($status === 1)
            {   // 进行中
                $indexCouponInfo = [];
                foreach ($item[1] as $index => $activeItem)
                {
                    if ($activeItem['start_time'] <= $this->time)
                    {
                        $activeItem['index'] = $index;
                        $indexCouponInfo = $activeItem; // 当前时间点的抢券信息
                    }
                }
                $flag1 = 1000000 + $day * 100;
                if ($indexCouponInfo)
                { // 抢券开始了
                    // 获取中奖用户
                    $giveCoupon1Uids = $isLogin ? $couponRecordModel->getActiveCouponGiveUids($this->activeFlag, $flag1) : [];
                    // 判断 自己 是否已经 抢到了优惠券
                    if (in_array($uid, $giveCoupon1Uids, false))
                    {   // 抢到了
                        $btn1Status = 4;    // 抢券成功【去使用】
                    } else
                    {   // 判断是否抢过了
                        if ($isLogin && $couponRecordModel->getUserCouponGiveInfo($this->activeFlag, $uid, $flag1 + $indexCouponInfo['index'] * 10))
                        {   // 抢过了
                            $btn1Status = 2;    // 已抢空
                        } else
                        {   // 没有抢过
                            $btn1Status = 1;    // 抢券中
                        }

                        if ($indexCouponInfo['index'] < 2)
                        {
                            $refreshTime1 = isset($item[1][$indexCouponInfo['index'] + 1]['start_time']) ? $item[1][$indexCouponInfo['index'] + 1]['start_time'] - $this->time : 0;
                        } else
                        {
                            $refreshTime1 = 0;
                        }
                    }
                } else
                { // 抢券还未开始
                    $btn1Status = 0;
                    $refreshTime1 = $item[1][1]['start_time'] - $this->time;  // 距离活动开始 剩余时间 秒
                }

                $flag2 = 200000 + 2024 * 10;
                $giveCoupon2Uids = $isLogin ? $couponRecordModel->getActiveCouponGiveUids($this->activeFlag, $flag2) : [];
                // 判断 自己 是否已经 抢到了优惠券
                if ($isLogin && in_array($uid, $giveCoupon2Uids, false))
                {   // 抢到了
                    $giveActiveCouponData = $couponRecordModel->getDataDetails($this->activeFlag, $uid, $flag2);
                    $btn2Status = $giveActiveCouponData['cid'] ? 6 : 5;    // 抢券成功【去使用】
                } else
                {   // 未抢到
                    $indexCouponInfo2 = [];
                    foreach ($item[2] as $index => $activeItem)
                    {
                        if ($activeItem['start_time'] <= $this->time)
                        {
                            $activeItem['index'] = $index;
                            $indexCouponInfo2 = $activeItem; // 当前时间点的抢券信息
                        }
                    }

                    if ($indexCouponInfo2)
                    {   // 判断是否抢过了
                        $flag2 = 200000 + $day * 10;
                        if ($isLogin && $couponRecordModel->getUserCouponGiveInfo($this->activeFlag, $uid, $flag2 + $indexCouponInfo2['index']))
                        {   // 抢过了
                            $btn2Status = 2;    // 已抢空
                        } else
                        {   // 没有抢过
                            $btn2Status = 1;    // 抢券中
                        }
                    } else
                    {   // 抢券还未开始
                        $btn2Status = 0;
                        $refreshTime2 = $item[2][1]['start_time'] - $this->time;  // 距离活动开始 剩余时间 秒
                    }
                }
            } else
            {   // 已结束
                $btn1Status = 3;
                $btn2Status = 3;
            }

            $giveCouponActive[] = [
                'date' => $day,
                'status' => $status,   // 0=>未开始 1=>进行中 2=>已结束
                'coupon_list' => [
                    [
                        'type' => 1,
                        'name' => '运势免费券/通用8折券',
                        'desc' => '免费券',
                        'tip' => '仅限准了APP使用',
                        'status' => $btn1Status,
                        'refresh_time' => $refreshTime1 ?? 0,
                    ],
                    [
                        'type' => 2,
                        'name' => '1对1连麦5分钟免费券',
                        'desc' => '免费券',
                        'tip' => '仅限准有好事APP使用',
                        'status' => $btn2Status,
                        'refresh_time' => $refreshTime2 ?? 0,
                    ],
                ],
            ];
        }
        // 获取获得的新字
        $newTextInfo = $isLogin ? $activeTextChangeRecodeModel->getUserNewTextInfo($this->activeFlag, $uid) : [];
        $newText = [];
        if ($newTextInfo)
        {
            foreach ($newTextInfo as $textItem => $textNum)
            {
                if ($textNum > 0)
                {
                    $newText[] = [
                        'text' => (string)$textItem,
                        'num' => (int)$textNum,
                    ];
                }
            }
        }
        // 好友索要
        if ($uen && in_array($requestText, $this->text, true))
        {
            if ($isLogin)
            {
                $uInfo2 = (new \app\common\cachemodel\User())->uenSearch($uid, $uen, 'id');
                if (!empty($uInfo2))
                {   // 用户存在
                    $requestData = [
                        'uen' => $uen,
                        'text' => $requestText,
                    ];
                }
            } else
            {
                $requestData = [
                    'uen' => $uen,
                    'text' => $requestText,
                ];
            }
        }
        // 获取用户拥有的字
        $userTextInfo = $isLogin ? $yearActiveTextModel->getUserTextInfo($this->activeFlag, $uid) : [];
        $resUserTextInfo = [];
        foreach ($this->text as $textItem)
        {
            $resUserTextInfo[] = [
                'text' => $textItem,
                'num' => isset($userTextInfo[$textItem]) ? (int)$userTextInfo[$textItem]['num'] : 0,
            ];
        }
        // --- 签到按钮状态信息
        if ($this->time < $this->activeConfig['sign_in']['start_time'])
        {  // 签到活动未开始
            $signInData = [
                'status' => 0,
                'btn_title' => '签到',
            ];
        } elseif ($this->time > $this->activeConfig['sign_in']['start_time'] && $this->time < $this->activeConfig['sign_in']['end_time'])
        {   // 活动进行中
            $isSignIn = $isLogin ? $activeTextChangeRecodeModel->getUserIsSignIn($this->activeFlag, $uid, $date) : false;
            if (!$isSignIn)
            {
                $signInData = [
                    'status' => 1,
                    'btn_title' => '签到',
                ];
            } else
            {
                $signInData = [
                    'status' => 0,
                    'btn_title' => $date === 216 ? '已签到，请尽快兑换奖励' : '已签到，明日再来',
                ];
            }
        } else
        {// 活动已结束
            $signInData = [
                'status' => 0,
                'btn_title' => '已结束，请尽快兑换奖励',
            ];
        }
        // 获取用户是否领券
        $isExchangeInfo = $isLogin ? $couponRecordModel->getUserCouponExchangeInfo($this->activeFlag, $uid, [1, 2]) : [];
        if ($isExchangeInfo)
        {
            $isExchange1 = isset($isExchangeInfo[1]) && $isExchangeInfo[1] ? 1 : 0;
            $isExchange2 = isset($isExchangeInfo[2]) && $isExchangeInfo[2] ? 1 : 0;
        } else
        {
            $isExchange1 = 0;
            $isExchange2 = 0;
        }

        $shareInfo = [
            'url' => Env::get('host.domain') . '/web/collect_cards/index_2024',
            'uen' => $this->user['uen'],
        ];

        $resData = [
            'give_coupon_active' => $giveCouponActive,
            'new_text' => $newText,
            'request_text' => $requestData ?? null,
            'text_have_num' => $resUserTextInfo,
            'is_exchange_coupon1' => $isExchange1,
            'is_exchange_coupon2' => $isExchange2,
            'sign_in_data' => $signInData,
            'share_info' => $shareInfo,
        ];

        return show(config('code.success'), '请求成功', $resData);
    }

    /**
     * 领取活动优惠券
     */
    public function getActivCoupon()
    {
        $type = input('type/d', 1);  // 1=>抢免费券/8折券 2=>抢准有好事连麦优惠券
        $date = input('date/d', 0);  // 209  月日 2024-02-09

        if (!isset($this->activeConfig['coupon'][$date]) || !in_array($type, [1, 2], true))
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }
        if (Util::commentCheck($this->user['id'], ['getActivCoupon', 'type' => $type, 'date' => $date], 1))
        {
            return show(config('code.error'), '操作频繁，请稍后再试～');
        }
        $couponActiveInfo = $this->activeConfig['coupon'][$date][$type];

        $couponRecordModel = new ZlYearActiveCouponRecord();

        if ($type === 1)
        {   // 领取   免费券
            $indexCouponInfo = [];
            foreach ($couponActiveInfo as $index => $activeItem)
            {
                if ($activeItem['start_time'] <= $this->time)
                {
                    $activeItem['index'] = $index;
                    $indexCouponInfo = $activeItem; // 当前时间点的抢券信息
                }
            }

            if (empty($indexCouponInfo))
            {
                return show(config('code.error'), '活动暂未开始');
            }

            $flag = 1000000 + $date * 100;
            // 判断当前用户是否已经抢到了优惠券
            $giveCoupon1Uids = $couponRecordModel->getActiveCouponGiveUids($this->activeFlag, $flag);
            // 判断 自己 是否已经 抢到了优惠券
            if (in_array($this->user['id'], $giveCoupon1Uids, false))
            {   // 抢到了
                return show(config('code.error'), '优惠券已领取过了');
            }

            if ($indexCouponInfo['end_time'] < $this->time)
            {
                if ($indexCouponInfo['index'] < 2)
                {
                    $refreshTime = isset($couponActiveInfo[$indexCouponInfo['index'] + 1]['start_time']) ? $couponActiveInfo[$indexCouponInfo['index'] + 1]['start_time'] - $this->time : 0;
                } else
                {
                    $refreshTime = 0;
                }
                // 记录用户已经抢过了
                $couponRecordModel->setUserCouponGiveInfo($this->activeFlag, $this->user['id'], $flag + $indexCouponInfo['index'] * 10);
                return show(config('code.success'), '当前抢券已结束', [
                    'status' => 2,
                    'refresh_time' => $refreshTime,
                ]);
            }
            // 获取当前发放数量 131 1 1
            $couponGiveInfo = $couponRecordModel->getActiveCouponGiveInfo($this->activeFlag);
            $num1 = $couponGiveInfo[$flag + $indexCouponInfo['index'] * 10 + 1] ?? 0;
            $num2 = $couponGiveInfo[$flag + $indexCouponInfo['index'] * 10 + 2] ?? 0;
            $resNum1 = max(5 - $num1, 0);
            $resNum2 = max(100 - $num2, 0);
            if ($resNum1 <= 0 && $resNum2 <= 0)
            {   // 没有优惠券 可领了
                if ($indexCouponInfo['index'] < 2)
                {
                    $refreshTime = isset($couponActiveInfo[$indexCouponInfo['index'] + 1]['start_time']) ? $couponActiveInfo[$indexCouponInfo['index'] + 1]['start_time'] - $this->time : 0;
                } else
                {
                    $refreshTime = 0;
                }
                // 记录用户已经抢过了
                $couponRecordModel->setUserCouponGiveInfo($this->activeFlag, $this->user['id'], $flag + $indexCouponInfo['index'] * 10);
                return show(config('code.success'), '哎呀、已经抢没了～', [
                    'status' => 3,
                    'refresh_time' => $refreshTime,
                ]);
            }
            $couponType = $this->getCouponType($resNum1, $resNum2);
            // 抢券
            $resNum = $couponRecordModel->ActiveCouponGiveChange($this->activeFlag, $flag + $indexCouponInfo['index'] * 10 + $couponType, 1);
            $couponNum = $couponType === 1 ? 5 : 100;
            if ($resNum > $couponNum)
            {
                $couponRecordModel->ActiveCouponGiveChange($this->activeFlag, $flag + $indexCouponInfo['index'] * 10, -1);

                if ($indexCouponInfo['index'] < 2)
                {
                    $refreshTime = isset($couponActiveInfo[$indexCouponInfo['index'] + 1]['start_time']) ? $couponActiveInfo[$indexCouponInfo['index'] + 1]['start_time'] - $this->time : 0;
                } else
                {
                    $refreshTime = 0;
                }
                // 记录用户已经抢过了
                $couponRecordModel->setUserCouponGiveInfo($this->activeFlag, $this->user['id'], $flag + $indexCouponInfo['index'] * 10);
                return show(config('code.success'), '哎呀、已经抢没了～', [
                    'status' => 3,
                    'refresh_time' => $refreshTime,
                ]);
            }
            // 抢券成功  给用户发放优惠券
            $cid = $couponType === 1 ? 750 : 758;

            $userCouponModel = new UserCoupon();
            $couponInfo = (new ZlCouponAttr())->getInfoById($cid, ['desc', 'type', 'rand_min', 'rand_max', 'ur_id', 'gids']);
            $cData = [
                'uid' => $this->user['id'],
                'c_id' => $cid,
                'ur_id' => $couponInfo['ur_id'],
                'start_time' => $this->time,
                'end_time' => strtotime("+30 day"),
                'give_time' => $this->time,
                'status' => 0,
                'price' => $couponInfo['type'] == 4 ? mt_rand($couponInfo['rand_min'], $couponInfo['rand_max']) : 0,
                'is_give' => 0,
                'create_time' => $this->time,
                'update_time' => 0,
            ];
            $ucId = $userCouponModel->insertGetId($cData);
            $ids[$ucId] = $ucId; // 添加未用于ID
            // 神策打点
            $gidsArr = explode(',', $couponInfo['gids']);
            $couponRangeArr = (new Goods())->where('id', 'in', $gidsArr)->column('name');
            // 神策打点 75 获得优惠券 AcquireCoupon
            SensorsData::track($this->user['id'], true, 'AcquireCoupon', [
                'refer_name' => '',
                'refer_link' => '',
                'coupon_name' => $couponInfo['desc'],
                'coupon_expire' => date('Y-m-d H:i:s', $cData['end_time']),
                'coupon_type' => $userCouponModel->couponTypeName[$couponInfo['type']],
                'coupon_range' => $couponRangeArr,
                'acquire_channel' => '2024春节活动-抢券',
                'is_give' => false,
                'acquire_scene' => '活动H5',
            ]);
            // 写入 活动中奖记录
            $couponRecordModel->save([
                'active_flag' => $this->activeFlag,
                'uid' => $this->user['id'],
                'type' => 1,
                'flag' => $flag,
                'cid' => $ucId,
                'create_time' => $this->time,
            ]);
            // 未使用
            $userCouponModel->listDataAdd($this->user['id'], $ids, 1);
            // 记录中奖用户
            $couponRecordModel->addActiveCouponGiveUid($this->activeFlag, $flag, $this->user['id']);
            // 记录用户已经抢过了
            $couponRecordModel->setUserCouponGiveInfo($this->activeFlag, $this->user['id'], $flag);
            return show(config('code.success'), '抢券成功', [
                'status' => 1,
                'refresh_time' => 0,
                'name' => $couponType === 1 ? '运势免费券' : '通用8折券',
                'des' => $couponType === 1 ? '免费券' : '折扣券',
            ]);
        } else
        {   // 领取折扣券
            $flag = 200000 + 2024 * 10;
            //  判断当前用户是否已经抢到了优惠券
            $giveCoupon2Uids = $couponRecordModel->getActiveCouponGiveUids($this->activeFlag, $flag);
            if (in_array($this->user['id'], $giveCoupon2Uids, false))
            {   // 抢到了
                return show(config('code.error'), '优惠券已领取过了');
            }
            $indexCouponInfo = [];
            foreach ($couponActiveInfo as $index => $activeItem)
            {
                if ($activeItem['start_time'] <= $this->time)
                {
                    $activeItem['index'] = $index;
                    $indexCouponInfo = $activeItem; // 当前时间点的抢券信息
                }
            }

            if (empty($indexCouponInfo))
            {
                return show(config('code.error'), '活动暂未开始');
            }

            if ($indexCouponInfo['end_time'] < $this->time)
            {
                if ($indexCouponInfo['index'] < 2)
                {
                    $refreshTime = isset($couponActiveInfo[$indexCouponInfo['index'] + 1]['start_time']) ? $couponActiveInfo[$indexCouponInfo['index'] + 1]['start_time'] - $this->time : 0;
                } else
                {
                    $refreshTime = 0;
                }
                // 记录用户已经抢过了
                $couponRecordModel->setUserCouponGiveInfo($this->activeFlag, $this->user['id'], $flag);
                return show(config('code.success'), '当前抢券已结束', [
                    'status' => 2,
                    'refresh_time' => $refreshTime,
                ]);
            }

            $resNum = $couponRecordModel->ActiveCouponGiveChange($this->activeFlag, $flag, 1);
            if ($resNum > $indexCouponInfo['coupon_num'])
            {
                $couponRecordModel->ActiveCouponGiveChange($this->activeFlag, $flag, -1);
                // 记录用户已经抢过了
                $couponRecordModel->setUserCouponGiveInfo($this->activeFlag, $this->user['id'], $flag);
                return show(config('code.success'), '哎呀、已经抢没了～', [
                    'status' => 3,
                    'refresh_time' => 0,
                ]);
            }
            // 写入 活动中奖记录
            $couponRecordModel->save([
                'active_flag' => $this->activeFlag,
                'uid' => $this->user['id'],
                'type' => 3,
                'flag' => $flag,
                'cid' => 0,
                'create_time' => $this->time,
            ]);
            // 记录中奖用户
            $couponRecordModel->addActiveCouponGiveUid($this->activeFlag, $flag, $this->user['id']);
            // 记录用户已经抢过了
            $couponRecordModel->setUserCouponGiveInfo($this->activeFlag, $this->user['id'], $flag);
            return show(config('code.success'), '抢券成功', [
                'status' => 1,
                'refresh_time' => 0,
                'name' => '1对1连麦5分钟免费券',
                'des' => '免费券',
            ]);
        }
    }

    public function giveZyshCoupon()
    {
        $uen = input('uen/s', '');
        if (Util::commentCheck($this->user['id'], ['giveZyshCoupon', 'uen' => $uen], 1))
        {
            return show(config('code.error'), '操作频繁，请稍后再试～');
        }
        $couponRecordModel = new ZlYearActiveCouponRecord();
        $flag2 = 200000 + 2024 * 10;
        $giveActiveCouponData = $couponRecordModel->getDataDetails($this->activeFlag, $this->user['id'], $flag2);
        if ($giveActiveCouponData['cid'])
        {
            return show(config('code.success'), '领取成功');
        }
        $zyhsUid = (new ZyhsUser())->where(['uen' => $uen])->value('id');
        if (!$zyhsUid)
        {
            return show(config('code.error'), '领取失败，准有好事ID不存在');
        }
        // 优惠券ID
        $cid = 750; // 准有好事 优惠券ID
        $startTime = $this->time;
        $endTime = strtotime('+30days', $startTime);
        $data = [
            'type' => 1,
            'uid' => $zyhsUid,
            'c_id' => $cid,
            'start_time' => $startTime,
            'end_time' => $endTime,
            'give_time' => 0,
            'status' => 0,
            'is_give' => 0,
            'create_time' => $this->time,
        ];
        $zyhsUserCouponModel = new ZyhsUserCoupon();
        $resId = $zyhsUserCouponModel->insertGetId($data);
        $zyhsUserCouponModel->listDataAdd($zyhsUid, [$resId => $resId], 1);
        // 更新 优惠券信息
        $couponRecordModel->setDataInfo($giveActiveCouponData['id'], $this->activeFlag, $this->user['id'], $flag2, (int)$resId);

        return show(config('code.success'), '领取成功');
    }

    /**
     * @param int $num1 免费券数量
     * @param int $num2 折扣券数量
     * @return int  1=>免费券 2=>折扣券
     */
    public function getCouponType(int $num1, int $num2): int
    {
        if ($num1 <= 0)
        {
            return 2;
        }

        if ($num2 <= 0)
        {
            return 1;
        }

        $total = $num1 + $num2;
        $n = mt_rand(1, $total);

        if ($num1 >= $n)
        {
            return 1;
        } else
        {
            return 2;
        }
    }

    /**
     * 签到
     */
    public function signIn()
    {
        $date = (int)(date('md', $this->time));

        $activeTextChangeRecodeModel = new ZlYearActiveTextChangeRecode();

        if ($this->time < $this->activeConfig['sign_in']['start_time'])
        { // 2024-02-09 00:00:00
            return show(config('code.error'), '活动未开始，签到失败～');
        }

        if ($this->time > $this->activeConfig['sign_in']['end_time'])
        { // 2024-02-17 00:00:00
            return show(config('code.error'), '活动已结束，签到失败～');
        }


//        测试，多次签到领券【注释掉下面四行】
        // 判断用户是否签到
        if ($activeTextChangeRecodeModel->getUserIsSignIn($this->activeFlag, $this->user['id'], $date))
        {
            return show(config('code.error'), '今日已经签到过了～');
        }

        $resData = $activeTextChangeRecodeModel->userSignIn($this->activeFlag, $this->user['id'], $date);

        if ($resData['status'])
        {
            // 神策打点 签到点击    ChineseNewYearCheckClick
            SensorsData::track($this->user['id'], true, 'ChineseNewYearCheckClick', [
                'check_date' => $this->activeConfig['coupon'][$date]['date'],
            ]);

            return show(config('code.success'), '签到成功', [
                'new_text' => $resData['text_info'],
                'sign_in_data' => [
                    'status' => 0,
                    'btn_title' => $date === 216 ? '已签到，请尽快兑换奖励' : '已签到，明日再来',
                ],
            ]);
        } else
        {
            return show(config('code.error'), '服务异常，请稍后再试～');
        }
    }

    public function exchangeCoupon()
    {
        $type = input('type/d', 1);
        $couponType = input('coupon_type/d', 0);
        if (!in_array($type, [1, 2], true) || ($type === 2 && !in_array($couponType, [1, 2, 3, 4, 5], true)) || ($type === 1 && !in_array($couponType, [1, 2, 3], true)))
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }
        $yearActiveTextModel = new ZlYearActiveText();
        $couponRecordModel = new ZlYearActiveCouponRecord();

        // 获取兑换的 优惠券cid
        if ($type === 1)
        {
            $typeName = [1 => 'year_fortune_cid', 2 => 'month_fortune_cid', 3 => 'day_fortune_cid'];
            $cid = $this->activeConfig['text_exchange']['text1'][$typeName[$couponType]];
        } else
        {
            $typeName = [1 => 'money_cid', 2 => 'feelings_cid', 3 => 'dating_cid', 4 => 'academic_cid', 5 => 'carrer_cid',];
            $cid = $this->activeConfig['text_exchange']['text2'][$typeName[$couponType]];
        }

        if ($couponRecordModel->getUserCouponIsExchangeInfo($this->activeFlag, $this->user['id'], $type))
        {
            return show(config('code.error'), '优惠券已经兑换过了～');
        }

        // 获取用户字信息
        $userTextInfo = $yearActiveTextModel->getUserTextInfo($this->activeFlag, $this->user['id']);

        $changeData = [];
        foreach (['2024', '愉', '跃', '龙', '门'] as $textItem)
        {
            if (!isset($userTextInfo[$textItem]) || $userTextInfo[$textItem]['num'] < 1)
            {
                return show(config('code.error'), '卡片未集齐，兑换失败');
            }

            $changeData[] = [
                'id' => $userTextInfo[$textItem]['id'],
                'text' => $textItem,
                'num' => $userTextInfo[$textItem]['num'] - 1,
                'change_num' => -1,
            ];
        }

        // if ($type === 2)
        // {
        //     if (!isset($userTextInfo[2024]) || $userTextInfo[2024]['num'] < 1)
        //     {
        //         return show(config('code.error'), '卡片未集齐，兑换失败');
        //     }
        //
        //     $changeData[] = [
        //         'id' => $userTextInfo[2024]['id'],
        //         'text' => '2024',
        //         'num' => $userTextInfo[2024]['num'] - 1,
        //         'change_num' => -1,
        //     ];
        // }
        $resData = $yearActiveTextModel->userChangeTextInfo($this->activeFlag, $this->user['id'], $changeData, 4);

        if ($resData)
        {   // 兑换成功 给用户添加优惠券
            $userCouponModel = new UserCoupon();
            $couponInfo = (new ZlCouponAttr())->getInfoById($cid, ['desc', 'type', 'rand_min', 'rand_max', 'ur_id', 'gids']);
            $cData = [
                'uid' => $this->user['id'],
                'c_id' => $cid,
                'ur_id' => $couponInfo['ur_id'],
                'start_time' => $this->time,
                'end_time' => strtotime("+30 day"),
                'give_time' => $this->time,
                'status' => 0,
                'price' => $couponInfo['type'] == 4 ? mt_rand($couponInfo['rand_min'], $couponInfo['rand_max']) : 0,
                'is_give' => 0,
                'create_time' => $this->time,
                'update_time' => 0,
            ];
            $ucId = $userCouponModel->insertGetId($cData);
            $ids[$ucId] = $ucId; // 添加未用于ID
            // 神策打点
            $gidsArr = explode(',', $couponInfo['gids']);
            $couponRangeArr = (new Goods())->where('id', 'in', $gidsArr)->column('name');
            // 神策打点 75 获得优惠券 AcquireCoupon
            SensorsData::track($this->user['id'], true, 'AcquireCoupon', [
                'refer_name' => '',
                'refer_link' => '',
                'coupon_name' => $couponInfo['desc'],
                'coupon_expire' => date('Y-m-d H:i:s', $cData['end_time']),
                'coupon_type' => $userCouponModel->couponTypeName[$couponInfo['type']],
                'coupon_range' => $couponRangeArr,
                'acquire_channel' => '春节活动-兑换',
                'is_give' => false,
                'acquire_scene' => '活动H5',
            ]);
            // 写入 活动中奖记录
            $couponRecordModel->save([
                'active_flag' => $this->activeFlag,
                'uid' => $this->user['id'],
                'type' => 2,
                'flag' => $type,    // 1兑换年运免费券  2兑换一生报告免费券
                'cid' => $ucId,
                'create_time' => $this->time,
            ]);
            // 未使用
            $userCouponModel->listDataAdd($this->user['id'], $ids, 1);
            // 记录用户已经抢过了
            $couponRecordModel->setUserCouponIsExchangeInfo($this->activeFlag, $this->user['id'], $type);

            return show(config('code.success'), '兑换成功', [
                'type' => 1,
                'name' => $couponInfo['desc'],
                'desc' => '免费券',
                'tip' => '有效期：30天内使用',
            ]);
        } else
        {
            return show(config('code.error'), '服务异常，请稍后再试～');
        }
    }

    /**
     * 卡片赠送
     * @return Json
     * @throws \Exception
     */
    public function sendText()
    {
        $text = input('text/s', '');
        $uen = input('uen/s', '');
        $type = input('type/d', 1);

        if (empty($uen) || !in_array($text, $this->text, true))
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }
        $yearActiveTextModel = new ZlYearActiveText();

        if ($this->user['uen'] === $uen) return show(config('code.error'), '被赠送用户不能是自己！');

        $uInfo2 = (new \app\common\cachemodel\User())->uenSearch((int)$this->user['id'], $uen, 'id');
        if (empty($uInfo2)) return show(config('code.error'), '被赠送用户不存在！');
        $uid2 = (int)$uInfo2['id'];

        // 获取用户字信息
        $userTextInfo = $yearActiveTextModel->getUserTextInfo($this->activeFlag, $this->user['id']);

        if (!isset($userTextInfo[$text]) || $userTextInfo[$text]['num'] < 2)
        {
            return show(config('code.error'), '卡片不足，赠送失败～');
        }

        // 赠送用户 卡片扣除
        $changeData1 = [
            [
                'id' => $userTextInfo[$text]['id'],
                'text' => $text,
                'num' => $userTextInfo[$text]['num'] - 1,
                'change_num' => -1,
            ],
        ];
        $resData = $yearActiveTextModel->userChangeTextInfo($this->activeFlag, $this->user['id'], $changeData1, 2, $uid2);
        if ($resData)
        {   // 受赠用户 卡片增加
            $userTextInfo2 = $yearActiveTextModel->getUserTextInfo($this->activeFlag, $uid2);
            if (isset($userTextInfo2[$text]))
            {
                $changeData2 = [
                    [
                        'id' => $userTextInfo2[$text]['id'],
                        'text' => $text,
                        'num' => $userTextInfo2[$text]['num'] + 1,
                        'change_num' => 1,
                    ],
                ];
            } else
            {
                $changeData2 = [
                    [
                        'text' => $text,
                        'num' => 1,
                        'change_num' => 1,
                    ],
                ];
            }
            $resData = $yearActiveTextModel->userChangeTextInfo($this->activeFlag, $uid2, $changeData2, 3, $this->user['id']);
            if ($resData)
            {
                (new ZlYearActiveTextChangeRecode())->userNewTextAdd($this->activeFlag, $uid2, $text);

                return show(config('code.success'), '赠送成功', [
                    'text' => $text,
                    'num' => $changeData1[0]['num'],
                ]);
            } else
            {
                Log::write("赠送卡片失败 扣除卡片成功->受赠用户卡片增加失败:【{$text}】uid2:{$uid2}", 'error');
            }

            // 神策打点 收到赠送    ChineseNewYearGetCard
            SensorsData::track($uid2, true, 'ChineseNewYearGetCard', [
                'card' => $text,
                'acquire_type' => $type === 1 ? '主动赠送' : '索要活动',
            ]);

            return show(config('code.success'), '赠送成功', [
                'text' => $text,
                'num' => $changeData1[0]['num'],
            ]);
        }

        return show(config('code.error'), '服务异常，请稍后再试～');
    }

    /**
     * 分享领取卡片
     * @return Json
     * @throws \Exception
     */
    public function shareGive()
    {
//        测试导航栏分享，必定获取券
//        return show(config('code.success'), '请求成功', [
//            'new_text' => ['2022'],
//        ]);
        $date = (int)(date('md', $this->time));

        $activeTextChangeRecodeModel = new ZlYearActiveTextChangeRecode();

        if ($this->time < $this->activeConfig['sign_in']['start_time'])
        { // 2024-02-09 00:00:00
            return show(config('code.success'), '请求成功', [
                'new_text' => [],
            ]);
        }

        if ($this->time > $this->activeConfig['sign_in']['end_time'])
        { // 2024-02-17 00:00:00
            return show(config('code.success'), '请求成功', [
                'new_text' => [],
            ]);
        }
        // 判断今天是否分享过了
        if ($activeTextChangeRecodeModel->getUserIsShare($this->activeFlag, $this->user['id'], $date))
        {
            return show(config('code.success'), '请求成功', [
                'new_text' => [],
            ]);
        }

        //领取卡片
        $resData = $activeTextChangeRecodeModel->userShare($this->activeFlag, $this->user['id'], $date);

        if ($resData['status'])
        {
            return show(config('code.success'), '请求成功', [
                'new_text' => $resData['text_info'],
            ]);
        } else
        {
            return show(config('code.success'), '请求成功', [
                'new_text' => [],
            ]);
        }
    }

    /**
     * 确认收下字
     * @return Json
     * @throws \Exception
     */
    public function knowNewText()
    {
        $text = input('text/s', '');

        if (!in_array($text, $this->text, true))
        {
            return show(config('code.success'), '请求成功');
        }

        (new ZlYearActiveTextChangeRecode())->userNewTextNumChange($this->activeFlag, $this->user['id'], $text);

        return show(config('code.success'), '请求成功');
    }
}
